package com.luckzj.sec.bridge;

import com.luckzj.sec.config.BridgeConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;

/**
 * Bridge http data, should remove Host
 */
public class HttpBridge extends PackageLoggingBridge{
    private String dstHost;

    public HttpBridge(BridgeConfig bridgeConfig) {
        super(bridgeConfig);

        dstHost = String.format("%s:%d", getBridgeConfig().getDstHost(), getBridgeConfig().getDstPort());
    }

    @Override
    protected void setupServerChannel(SocketChannel ch) {
        super.setupServerChannel(ch);

        ch.pipeline().addLast(new HttpRequestDecoder(), new HttpResponseEncoder());
        ch.pipeline().addLast(new HttpBridgeModifier());
    }

    @Override
    protected void setupClientChannel(SocketChannel ch) {
        super.setupClientChannel(ch);

        ch.pipeline().addLast(new HttpResponseDecoder(), new HttpRequestEncoder());
    }

    public class HttpBridgeModifier extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof DefaultHttpRequest) {
                ((DefaultHttpRequest)msg).headers().set("Host", dstHost);
            }

            super.channelRead(ctx, msg);
        }
    }
}
